package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.reggie.common.R;
import com.example.reggie.entity.User;
import com.example.reggie.service.UserService;
import com.example.reggie.utils.Sample;
import com.example.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.rmi.CORBA.Util;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/sendMsg")
    public R<String>   sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if(phone!=null)
        {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
//            Sample.semdMsg(phone,code);
            log.info(code);
            session.setAttribute(phone,code);
            return  R.success("验证码发送成功");
        }
        return null;
    }

    @PostMapping("login")
    public  R<User> login(@RequestBody Map<String,String> map,HttpSession session)
    {
        String code = map.get("code");
        String phone = map.get("phone").toString();

        if(code.equals(session.getAttribute(phone))){
            LambdaQueryWrapper<User> userQuery = new LambdaQueryWrapper<>();
            userQuery.eq(User::getPhone,phone);
            User user = userService.getOne(userQuery);
            if(user==null)
            {
                 user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return  R.success(user);

        }

       return R.error("登录失败");

    }
}
